package com.hethongviet.preventingmachine.helps.db;

import java.util.ArrayList;
import java.util.List;

import com.hethongviet.preventingmachine.Utils;
import com.hethongviet.preventingmachine.models.Client;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class ClientSQLite
{
	public static final String TABLE_NAME = "client";

	public static final String COLUMN_ID_DB = "idDB";

	public static final String COLUMN_DEVICE_NUMBER = "device_number";
	public static final String COLUMN_DEVICE_NAME = "device_name";
	public static final String COLUMN_ALARM_PATH = "alarm_path";
	public static final String COLUMN_IS_CONTROLLED = "is_controlled";
	public static final String COLUMN_IS_ALARMED = "is_alarmed";

	// Database fields
	private SQLiteDatabase _database;
	private MySQLiteHelper _dbHelper;
	private String[] _allColumns = { COLUMN_ID_DB,

	COLUMN_DEVICE_NUMBER, COLUMN_DEVICE_NAME, COLUMN_ALARM_PATH,
			COLUMN_IS_ALARMED, COLUMN_IS_CONTROLLED };

	public static final String STRING_COLUMNS = COLUMN_ID_DB
			+ " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, "

			+ COLUMN_DEVICE_NUMBER + " text, " + COLUMN_DEVICE_NAME + " text, "
			+ COLUMN_ALARM_PATH + " text, " + COLUMN_IS_ALARMED + " integer, "
			+ COLUMN_IS_CONTROLLED + " integer";

	public ClientSQLite(Context context, String databaseName)
	{
		_dbHelper = new MySQLiteHelper(context, null, null, databaseName);
	}

	public void open() throws SQLException
	{
		_database = _dbHelper.getWritableDatabase();
	}

	public void close()
	{
		_dbHelper.close();
	}

	private boolean dataExist(Client client, Cursor cursor)
	{
		if (cursor == null)
		{
			return false;
		}
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext())
		{
			long idDB = cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB));
			if (idDB == client.getIdDB())
				return true;
		}
		return false;
	}

	/**
	 * @param client
	 * @return row id -1: insert fail
	 */
	public long insert(Client client)
	{
		Utils.debug("insert -- " + TABLE_NAME + " : admin");
		open();

		Cursor cursor = _database.rawQuery("SELECT * FROM " + TABLE_NAME
				+ " WHERE " + COLUMN_ID_DB + " = " + client.getIdDB(), null);

		long temp = -1;
		if (!dataExist(client, cursor))
		{
			Utils.debug("insert 1111111111111 INSERT");
			/* Insert to database */
			/* Insert new */
			Cursor cursorInsert = _database.rawQuery("INSERT INTO "
					+ TABLE_NAME + "(" + COLUMN_DEVICE_NUMBER + ", " + COLUMN_DEVICE_NAME + ", "
					+ COLUMN_ALARM_PATH + ", " + COLUMN_IS_ALARMED + ", "
					+ COLUMN_IS_CONTROLLED + ") values( ?, ?, ?, ?, ?)",

			new String[] { client.getDeviceNumber(), client.getDeviceName(), client.getAlarmPath(),
					client.isAlarmed() ? "1" : "0",
					client.isControlled() ? "1" : "0" });

			cursorInsert.moveToFirst();
			if (!cursorInsert.isAfterLast())
				temp = cursorInsert.getLong(cursorInsert
						.getColumnIndex(COLUMN_ID_DB));

			cursorInsert.close();
		}
		else
		{
			Utils.debug("insert 1111111111111 update");
			ContentValues contentValues = new ContentValues();
			contentValues.put(COLUMN_DEVICE_NUMBER, client.getDeviceNumber());
			contentValues.put(COLUMN_DEVICE_NAME, client.getDeviceName());
			contentValues.put(COLUMN_ALARM_PATH, client.getAlarmPath());
			contentValues
					.put(COLUMN_IS_ALARMED, client.isAlarmed() ? "1" : "0");
			contentValues.put(COLUMN_IS_CONTROLLED, client.isControlled() ? "1"
					: "0");

			temp = _database.update(TABLE_NAME, contentValues, COLUMN_ID_DB
					+ " = " + client.getIdDB(), null);
		}
		cursor.close();
		close();
		return temp;
	}

	public void deleteAll()
	{
		open();

		System.out.println("project deleted all");
		// _database.rawQuery("DELETE FROM " + TABLE_NAME, null); not work
		// _database.rawQuery("DELETE FROM " + TABLE_NAME + " WHERE 1", null);
		_database.delete(TABLE_NAME, "1", null);
		close();
	}

	public List<Client> getAll()
	{
		open();

		List<Client> listClients = new ArrayList<Client>();

		Cursor cursor = _database.query(TABLE_NAME, _allColumns, null, null,
				null, null, null);
		cursor.moveToFirst();
		while (!cursor.isAfterLast())
		{
			Client client = cursorToClient(cursor);
			listClients.add(client);
			cursor.moveToNext();
		}
		// Make sure to close the cursor
		cursor.close();
		close();
		return listClients;
	}

	private Client cursorToClient(Cursor cursor)
	{
		Client client = new Client();
		client.setIdDB(cursor.getLong(cursor.getColumnIndex(COLUMN_ID_DB)));
		client.setDeviceNumber(cursor.getString(cursor
				.getColumnIndex(COLUMN_DEVICE_NUMBER)));
		client.setDeviceName(cursor.getString(cursor
				.getColumnIndex(COLUMN_DEVICE_NAME)));
		client.setAlarmPath(cursor.getString(cursor
				.getColumnIndex(COLUMN_ALARM_PATH)));
		client.setAlarmed(cursor.getInt(cursor
				.getColumnIndex(COLUMN_IS_ALARMED)) == 1);
		client.setControlled(cursor.getInt(cursor
				.getColumnIndex(COLUMN_IS_CONTROLLED)) == 1);
		return client;
	}

	public final boolean isTableExist()
	{
		open();

		boolean isExist = false;
		Cursor cursor = _database.rawQuery(
				"select DISTINCT tbl_name from sqlite_master where tbl_name = '"
						+ TABLE_NAME + "'", null);
		isExist = cursor != null && cursor.getCount() > 0;

		cursor.close();
		close();

		return isExist;
	}
}
